package controllers

import (
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"zuoye_2/cache"
	"zuoye_2/models"
)

type Usercontroller struct {
	beego.Controller
}

func (c *Usercontroller) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "用户名或密码不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	uu := models.User{
		Username: username,
		Password: password,
	}
	err := models.DB.Debug().Where("username=?", username).Limit(1).Find(&uu).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "参数错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if uu.ID == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "用户名不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	key := fmt.Sprintf("user_login_%d", models.User{}.ID)
	Count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if Count >= 3 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "密码错误三次拦截成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if uu.Password != password {
		cache.Rdb.Incr(cache.Ctx, key).Result()
		if Count == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
		}
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "登陆失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "登录成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
